<?php
namespace Crm\Controller;

use Zend\View\Model\ViewModel;
use Crm\Common\CaptchaHelper;
use Zend\Session\SessionManager;
use Zend\Authentication\AuthenticationService;
use Zend\Mvc\Controller\AbstractActionController;

class LoginController extends AbstractActionController
{
    protected $crmUserTable;
    protected $organizationTable;
    protected $userGroupTable;

    public function indexAction()
    {
        $view = new ViewModel();
        return $view->setTerminal(true);
    }
    public function successAction()
    {
        return new ViewModel();
    }
    public function loginSubmitAction(){
        $request = $this->getRequest();
    
        $user_account = $request->getPost('user_account');
        $user_password = $request->getPost('user_password');
        $verif_code = $request->getPost('verif_code');
        if(empty($_SESSION['captcha_code']) || strtolower($_SESSION['captcha_code']) != strtolower(trim($verif_code))) {
            
            $this->flashMessenger()->addErrorMessage("验证码有误！请重新输入");
            return $this->redirect()->toRoute('crm/login');
        }
        
        if ($request->isPost()) {
            
            $result = $this->getCrmUserTable()->findByAccountPwd(trim($user_account), md5(md5(trim($user_password))));

            
            if ($result && $result['user_status']) {
                $_SESSION['account']['user_id'] = $result['user_id'];
                $_SESSION['account']['user_account'] = $result['user_account'];
                $_SESSION['account']['user_group_id'] = $result['user_group_id'];
                $_SESSION['account']['user_name'] = $result['user_name'];
                $_SESSION['account']['org_id'] = $result['org_id'];
                
                $this->flashMessenger()->addSuccessMessage("登录成功！");
                return $this->redirect()->toRoute('crm/login',array('action'=>'success'));
            } else {
        
                $this->flashMessenger()->addErrorMessage("登录失败！");
                return $this->redirect()->toRoute('crm/login', array(
                    'action' => 'index'
                ));
            }
        }
    
    
    }
    
    public function logoutAction(){
        $auth = new AuthenticationService();
        if($auth->hasIdentity()){
            $auth->clearIdentity();
        }
        $manager      = new SessionManager();
        $manager->destroy();
        return $this->redirect()->toRoute('crm/login');
    }
    
    public function captchaAction(){

        $captcha_service = new CaptchaHelper();
        $captcha_service->doimg();
        $_SESSION['captcha_code'] = $captcha_service->getCode();
        
    }
    public function changePasswordAction()
    {
        if($this->request->isPost()){
            $crmUserTable = $this->getCrmUserTable();
            $data = $this->request->getPost()->toArray();
            $crmUser=array(
                'user_name'=>$data['user_name'],
                'user_position'=>$data["user_position"],
                'org_id'=>$data["org_id"],
                'user_group_id'=>$data["user_group_id"],
            );
            try{
                if($data['user_password'] != $data['user_password_old']){
                    $crmUser['user_password']=md5(md5($data['user_password']));
                }
                $crmUserTable->updateItem($_SESSION['account']['user_id'],$crmUser);
            
                $this->flashMessenger()->addSuccessMessage("修改成功！");
                return $this->redirect()->toRoute('crm/login',array('action'=>'change-password'));
            }catch(\Exception $e)
            {
                die($e);
                $this->flashMessenger()->addErrorMessage("修改失败！");
                return $this->redirect()->toRoute('crm/login',array('action'=>'change-password'));
            }
        }else{
            $organizationList = array();
            $organizationList = $this->getOrganizationTable()->findAll();
            $groupList = array();
            $groupList = $this->getUserGroupTable()->findAll();
    
            //$data = $this->request->getQuery();
    
            $crmUserTable=$this->getCrmUserTable();
            $crmUser = $crmUserTable->getCrmUserById($_SESSION['account']['user_id']);
            $crmUser['user_password_old']=$crmUser['user_password'];
    
            return new ViewModel(array(
                'user'=>$crmUser,
                'organization'=>$organizationList,
                'groupList'=>$groupList,
            ));
        }
    }
    protected function getCrmUserTable()
    {
        return $this->getTable($this->crmUserTable,'Crm\Table\CrmUserTable');
    }
    protected function getOrganizationTable()
    {
        return $this->getTable($this->organizationTable,'Crm\Table\OrganizationTable');
    }
    protected function getUserGroupTable()
    {
        return $this->getTable($this->userGroupTable,'Crm\Table\UserGroupTable');
    }

    
    private function getTable($table,$table_name) {
        if (!$table) {
            $sm = $this->getServiceLocator();
            $table = $sm->get($table_name);
        }
        return $table;
    }
    
    

    
}